package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.user.dao.AccountDao;
import com.woniu.user.exception.WebException;
import com.woniu.user.exception.WebExceptionCode;
import com.woniu.user.model.Account;
import com.woniu.user.model.Coach;
import com.woniu.user.model.Sign;
import com.woniu.user.dao.SignDao;
import com.woniu.user.model.SignLog;
import com.woniu.user.service.AccountService;
import com.woniu.user.service.CoachService;
import com.woniu.user.service.SignLogService;
import com.woniu.user.service.SignService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.service.dto.AccountDto;
import com.woniu.user.service.dto.SignCoachDto;
import com.woniu.user.util.BeanCopyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 签约表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-02-15
 */
@Service
public class SignServiceImpl extends ServiceImpl<SignDao, Sign> implements SignService {
    @Resource
    private SignDao signDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private CoachService coachService;
    @Resource
    private AccountService accountService;
    @Resource
    private SignLogService signLogService;
    @Resource
    private SignService signService;
    @Override
    public IPage<Account> findMyStu(Integer userId, String condition, Integer current, Integer size) {
        Integer coachId = coachService.getOne(new QueryWrapper<Coach>().eq("account_id", userId)).getCoachId();
        IPage<Sign> signPage = new Page<>(current == null ? 1 : current, size == null ? 4 : size);
        IPage<Account> page = new Page<>(current == null ? 1 : current, size == null ? 4 : size);
        List<Account> accounts = new ArrayList<>();
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<Sign>().eq("coach_id", coachId);
        if (!(condition == null || "".equals(condition))) {
            //条件查询
            queryWrapper.eq("nickname", condition)
                    .or().eq("phone", condition)
                    .or().eq("gender", condition)
                    .or().eq("age", condition);
        }
        IPage<Sign> signIPage = signDao.selectPage(signPage, queryWrapper);
        List<Sign> signList = signDao.selectList(queryWrapper);
        for (Sign sign : signList) {
            Account account = accountDao.selectById(sign.getUserId());
            accounts.add(account);
        }
        page.setRecords(accounts);
        page.setTotal(signIPage.getTotal());
        return page;


    }

    @Override
    public void delStu(Integer userId, Integer accountId) {
        Sign sign = signDao.selectOne(new QueryWrapper<Sign>()
                .eq("coach_id", userId)
                .eq("user_id", accountId));
        removeById(sign);

    }

    // 学员签约
    @Override
    public void build(Integer coachId, Integer userId) {
        Coach coach = coachService.getById(coachId);
        if (coach == null) throw new WebException(WebExceptionCode.COACH_IS_NOT_EXISTS);
        Account user = accountService.getById(userId);
        if (user == null) throw new WebException(WebExceptionCode.USER_IS_NOT_EXISTS);

        Sign one = signService.getOne(new QueryWrapper<Sign>().eq("user_id", userId).eq("coach_id", coachId));
        if(one != null) throw new WebException(WebExceptionCode.SIGN_HAS_EXISTS);

        Sign sign = new Sign();// 签约表
        sign.setCoachId(coach.getCoachId());
        sign.setCoachName(coach.getRealname());
        sign.setUserId(user.getAccountId());
        sign.setUserName(user.getUsername());
        signService.save(sign);
        Sign newSign = signService.getOne(new QueryWrapper<Sign>().eq("user_id", user.getAccountId()).eq("coach_id", coach.getCoachId()));
        SignLog signLog = new SignLog();// 签约日志表
        signLog.setSignTime(LocalDateTime.now());
        signLog.setCoachId(coach.getCoachId());
        signLog.setCoachName(coach.getRealname());
        signLog.setUserId(user.getAccountId());
        signLog.setUserName(user.getUsername());
        signLog.setSignId(newSign.getSignId());
        signLogService.save(signLog);
    }

    // 解约
    @Override
    public void dissmiss(Integer userId, Integer coachId) {
        Account user = accountService.getById(userId);
        if (user == null) throw new WebException(WebExceptionCode.USER_IS_NOT_EXISTS);
        UpdateWrapper<Sign> wrapper = new UpdateWrapper<Sign>().eq("user_id", userId).eq("coach_id", coachId);
        Integer signId = signService.getOne(wrapper).getSignId();
        boolean flag = signService.remove(wrapper);
        if (!flag) throw new WebException(WebExceptionCode.DELETE_FAILED);
        SignLog signLog = signLogService.getById(signId);
        signLog.setBrokingTime(LocalDateTime.now());
        signLogService.updateById(signLog);
    }

    @Override
    public IPage<SignCoachDto> findMyCoach(Integer userId, String condition, Integer current, Integer size) {
        Page<SignCoachDto> page = new Page<>(current == null ? 1 : current, size == null ? 4 : size);
        List<SignCoachDto> coachs = new ArrayList<>();
        //找到所有签约的教练
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<Sign>();
        queryWrapper.eq("user_id", userId);
        if (condition != null && !"".equals(condition)) {
            //条件查询
            queryWrapper.like("user_name", condition);
        }
        List<Sign> signList = signDao.selectList(queryWrapper);
        for (Sign sign : signList) {
            Coach coach = coachService.getById(sign.getCoachId());
            SignCoachDto signCoachDto = BeanCopyUtil.copyObject(coach, SignCoachDto.class);
            signCoachDto.setCoachName(sign.getCoachName());
            coachs.add(signCoachDto);
        }
        Page<SignCoachDto> myCoach = page.setRecords(coachs);
        return myCoach;
    }

    // 获取我的所有签约教练
    @Override
    public IPage<SignCoachDto> getMyCoach(Page<Sign> pageInfo, Integer userId) {
        IPage<Sign> myCoach = this.baseMapper.selectByUserId(pageInfo, userId);
        List<Sign> records = myCoach.getRecords();
        ArrayList<SignCoachDto> signs = new ArrayList<>();
        for (Sign record : records) {
            Coach coach = coachService.getById(record.getCoachId());
            SignCoachDto signCoachDto = BeanCopyUtil.copyObject(coach, SignCoachDto.class);
            signCoachDto.setCoachName(record.getCoachName());
            signs.add(signCoachDto);
        }
        IPage<SignCoachDto> coachList = new Page<>();
        coachList.setRecords(signs);
        coachList.setCurrent(myCoach.getCurrent());
        coachList.setPages(myCoach.getPages());
        coachList.setSize(myCoach.getSize());
        coachList.setTotal(myCoach.getTotal());
        return coachList;
    }
}
